<template>
	<NavBar icon="left" title="修改密码" />
	<view class="h-screen bg-[#f2f2f2] p-2 ">
		<view class="bg-white rounded-md p-2 ">
			<uv-form labelWidth="80" labelPosition="left" :model="userInfo" :rules="rules" ref="form">
				<uv-form-item label="旧密码:" prop="oldPassword" borderBottom>
					<uv-input placeholder="请输入旧密码" v-model=" userInfo.oldPassword" border="none">
					</uv-input>
				</uv-form-item><uv-form-item label="新密码:" prop="newPassword" borderBottom>
					<uv-input type="password" placeholder="请输入新密码" v-model=" userInfo.newPassword" border="none">
					</uv-input>
				</uv-form-item>
				<uv-form-item label="新密码:" prop="reNewPassword" borderBottom>
					<uv-input type="password" placeholder="确认密码" v-model=" userInfo.reNewPassword" border="none">
					</uv-input>
				</uv-form-item>
			</uv-form>
		</view>
		<uv-button type="primary" text="提交" customStyle="margin-top: 10px" @click="submit"></uv-button>
	</view>
</template>

<script setup>
	import store from '@/store/index.js'
	import * as api from '@/api/modules/user.js'

	const userInfo = ref({
		oldPassword: '',
		reNewPassword: '',
		newPassword: '',
		userId: '',
	}) 
	const rules = ref({
		'oldPassword': [{
				type: 'string',
				required: true,
				message: '请输入旧密码',
				trigger: ['blur', 'change']
			},
			{
				min: 5,
				max: 20,
				message: '请输入5-20位密码',
				trigger: ['blur', 'change']
			}
		],
		'newPassword': [{
				type: 'string',
				required: true,
				message: '请输入新密码',
				trigger: ['blur', 'change']
			},
			{
				min: 5,
				max: 20,
				message: '请输入5-20位密码',
				trigger: ['blur', 'change']
			},
			{ // 自定义验证函数，见上说明，注意这里面的逻辑不能出现语法报错，否则可能导致不验证
				validator: (rule, value, callback) => {
					return  userInfo.value.reNewPassword === value
				},
				message: '两次密码不一致',
				trigger: ['blur'],
			}
		],
		'reNewPassword': [{
				type: 'string',
				required: true,
				message: '请输入新密码',
				trigger: ['blur']
			},
			{
				min: 5,
				max: 20,
				message: '请输入5-20位密码',
				trigger: ['blur']
			},
			{
				// 自定义验证函数，见上说明，注意这里面的逻辑不能出现语法报错，否则可能导致不验证
				validator: (rule, value, callback) => {
					return userInfo.value.newPassword === value
				},
				message: '两次密码不一致',
				trigger: ['blur', 'change']
			}
		],
	})
    const form = ref() 
	const submit = () => {
		if (userInfo.value.newPassword !== userInfo.value.reNewPassword) return uni.showToast({
			title: '两次新密码不一致',
			icon: 'none'
		}) 
		form.value.validate().then(async _ => {
			userInfo.value.newPassword = btoa(userInfo.value.newPassword)
			userInfo.value.oldPassword = btoa(userInfo.value.oldPassword)
			delete userInfo.value.reNewPassword
			await api.setUserPassward({
				...userInfo.value
			})
		}).catch(() => {})
	}
	userInfo.value.userId = store().user.userInfo.userId
</script>

<style lang="scss">

</style>